<template>
  <div class="app-container">
    <el-tabs v-model="activeName">
      <el-tab-pane label="中国主导相关指标" name="first">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px"
                 class="center">
          <el-form-item label="体系名称" prop="indicatorSystem.systemNameTab1"> <!-- 修改 prop 绑定 -->
            <el-input
              :rules="rulesFirst"
            v-model="indicatorSystem.systemNameTab1"
            placeholder="请输入体系名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-button icon="el-icon-refresh" size="mini" @click="reset">重置</el-button>
          <el-button type="primary" icon="el-icon-search" size="mini" v-hasPermi="['system:system:add']"  @click="addSystem">新建</el-button>
        </el-form>
        <el-row :gutter="20">
          <!--  左边表-->
          <el-col :span=6>
            <el-tree
              :data="dataListTab1"
              :props="defaultProps"
              @check-change="handleSelect"
              node-key="id"
              :expand-on-click-node="false"
              :highlight-current="true"
              :default-expand-all="true"
              show-checkbox
              ref="tree"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span style="flex: 1; margin-right: 8px;">{{ data.indicatorName }}</span>
                <!--        <span>{{ data.description }}</span>-->
              </span>
            </el-tree>
          </el-col>
          <el-col :span=18>
            <el-table v-if="activeName == 'first'" v-loading="loading" :data="dataList2" @selection-change="handleSelect" row-key="id" default-expand-all="true">
              <el-table-column label="指标名称" align="left" prop="indicatorName" :show-overflow-tooltip="true"/>
              <el-table-column label="指标介绍" align="center" prop="description" :show-overflow-tooltip="true"/>
              <el-table-column label="主观权重" align="center" class-name="small-padding fixed-width" width="150">
                <template slot-scope="scope">
                  <div v-if="!scope.row.children || scope.row.children.length === 0">
                    <el-input-number
                      v-model="weightMapTab1[scope.row.id]"
                    :min="0"
                    :max="1"
                    :step="0.01"
                    :precision="2"
                    :controls="false"
                    placeholder="必填(0-1)"
                    style="width: 110px"
                    @change="handleWeightChange(scope.row.id, $event, 'tab1')"
                    />
                    <span v-if="!weightMapTab1[scope.row.id] && weightMapTab1[scope.row.id] !== 0"
                    class="required-tip">*必填</span>
                  </div>
                  <span v-else style="color: #999;">-</span>
                </template>
              </el-table-column>
            </el-table>
          </el-col>

        </el-row>
      </el-tab-pane>
      <el-tab-pane label="中国参与相关指标" name="second">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px"
                 class="center">
          <el-form-item label="体系名称" prop="indicatorSystem.systemNameTab2"> <!-- 修改 prop 绑定 -->
            <el-input
              :rules="rulesSecond"
            v-model="indicatorSystem.systemNameTab2"
            placeholder="请输入体系名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-button icon="el-icon-refresh" size="mini" @click="reset">重置</el-button>
          <el-button type="primary" icon="el-icon-search" size="mini" v-hasPermi="['system:system:add']"  @click="addSystem2">新建</el-button>
        </el-form>
        <el-row :gutter="20">
          <!--  左边表 -->
          <el-col :span=6>
            <el-tree
              :data="dataListTab2"
              :props="defaultProps"
              @check-change="handleSelect2"
              node-key="id"
              :expand-on-click-node="false"
              :highlight-current="true"
              :default-expand-all="true"
              show-checkbox
              ref="tree2"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span style="flex: 1; margin-right: 8px;">{{ data.indicatorName }}</span>
                <!--        <span>{{ data.description }}</span>-->
              </span>
            </el-tree>
          </el-col>
          <el-col :span=18>
            <el-table v-if="activeName == 'second'" v-loading="loading" :data="dataList3" @selection-change="handleSelect2" row-key="id" default-expand-all="true">
              <el-table-column label="指标名称" align="left" prop="indicatorName" :show-overflow-tooltip="true"/>
              <el-table-column label="指标介绍" align="center" prop="description" :show-overflow-tooltip="true"/>
              <el-table-column label="主观权重" align="center" class-name="small-padding fixed-width" width="150">
                <template slot-scope="scope">
                  <div v-if="!scope.row.children || scope.row.children.length === 0">
                    <el-input-number
                      v-model="weightMapTab2[scope.row.id]"
                    :min="0"
                    :max="1"
                    :step="0.01"
                    :precision="2"
                    :controls="false"
                    placeholder="必填(0-1)"
                    style="width: 110px"
                    @change="handleWeightChange(scope.row.id, $event, 'tab2')"
                    />
                    <span v-if="!weightMapTab2[scope.row.id] && weightMapTab2[scope.row.id] !== 0"
                    style="color: red; font-size: 12px; margin-left: 5px;">*</span>
                  </div>
                  <span v-else style="color: #999;">-</span>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>

  </div>
</template>

<script>
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";
import {getIndicatorsTree} from "@/api/indicator/indicator";
import {addSystem} from "@/api/indicator/system";

export default {
  name: "newIndex",
  dicts: ['sys_show_hide', 'sys_normal_disable'],
  components: { IconSelect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 菜单表格树数据
      menuList: [],
      // 菜单树选项
      menuOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部折叠
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        visible: undefined
      },
      // 修改 indicatorSystem 结构，为两个标签页分别存储名称和权重
      indicatorSystem: {
        systemType: '',
        systemNameTab1: '', // 中国主导体系名称
        systemNameTab2: '', // 中国参与体系名称
        // indicatorSystem: { // 移除旧的嵌套结构
        //   systemName: ''
        // },
        indicatorWeight: [] // 权重列表，提交前动态填充
      },
      // 表单参数
      form: {},
      // 表单校验规则 - 现在直接绑定到 indicatorSystem 的字段
      rulesFirst: {
        systemNameTab1: [ // 直接对应新的数据结构
          { min: 1, max: 40, message: '长度在 1 到 40 个字符', trigger: 'blur' },
          { required: true, message: '体系名称不可为空！', trigger: 'blur' }
        ]
      },
      rulesSecond: {
        systemNameTab2: [ // 直接对应新的数据结构
          { min: 1, max: 40, message: '长度在 1 到 40 个字符', trigger: 'blur' },
          { required: true, message: '体系名称不可为空！', trigger: 'blur' }
        ]
      },
      dataList: [],
      dataList2: [],
      dataList3: [],
      dataListTab1: [],  // 第一个标签页的数据
      dataListTab2: [],  // 第二个标签页的数据
      activeName: 'first', // 当前激活的标签页
      selectedNodes1: [],
      selectedNodes2: [],
      // 分别为两个标签页管理权重映射
      weightMapTab1: {},  // 中国主导标签页权重映射
      weightMapTab2: {},  // 中国参与标签页权重映射
      defaultProps: {
        //树形控件的属性绑定对象
        children: "children", //设置通过children属性展示子节点信息
        label: "indicatorName", //通过label设置树形节点文本展示
        isLeaf: "!children",
      },
      allSelectedNodes1: [],
      allSelectedNodes2: []
    };
  },
  created() {
    this.getList();
  },
  computed: {

  },
  methods: {
    /** 处理权重变化 - 接收标签页标识 */
    handleWeightChange(id, value, tabName) {
      let targetMap = this.weightMapTab1;
      if (tabName === 'tab2') {
        targetMap = this.weightMapTab2;
      }
      // 使用 $set 确保响应式更新
      this.$set(targetMap, id, value);
    },

    /** 验证输入值 */
    validateInput(value, id){
      if (value === null || value === '' || value === undefined) {
        this.$message.warning('权重值不能为空');
        return false;
      }
      if (value < 0 || value > 1) {
        this.$message.warning('权重值必须在 0-1 之间');
        return false;
      }
      return true;
    },

    /** 获取所有叶子节点（没有子节点的节点） */
    getLeafNodes(nodes, leafNodes = []) {
      nodes.forEach(node => {
        if (!node.children || node.children.length === 0) {
          leafNodes.push(node.id);
        } else {
          this.getLeafNodes(node.children, leafNodes);
        }
      });
      return leafNodes;
    },

    /** 验证指定标签页的所有叶子节点是否都填写了权重 */
    validateAllWeights(selectedNodes, tabName) { // 接收标签页标识
      // 获取当前表单数据列表
      const dataList = tabName === 'tab2' ? this.dataList3 : this.dataList2;
      const weightMap = tabName === 'tab2' ? this.weightMapTab2 : this.weightMapTab1; // 使用对应标签页的权重映射

      // 获取所有叶子节点
      const leafNodes = this.getLeafNodes(dataList);

      // 检查每个叶子节点是否都有权重
      const missingWeights = [];
      leafNodes.forEach(nodeId => {
        const weight = weightMap[nodeId]; // 从对应标签页的权重映射中查找
        if (weight === undefined || weight === null || weight === '') {
          // 找到对应的节点名称
          const findNodeName = (nodes, id) => {
            for (let node of nodes) {
              if (node.id === id) return node.indicatorName;
              if (node.children) {
                const found = findNodeName(node.children, id);
                if (found) return found;
              }
            }
            return null;
          };
          const nodeName = findNodeName(this.dataList, nodeId);
          if (nodeName) missingWeights.push(nodeName);
        }
      });

      if (missingWeights.length > 0) {
        this.$message.error(`以下指标的主观权重未填写：${missingWeights.join('、')}`);
        return false;
      }

      return true;
    },

    addSystem() {
      // 1. 验证当前标签页的体系名称 (使用 form 的验证)
      if (!this.indicatorSystem.systemNameTab1) {
        this.$modal.msgError("中国主导体系名称不可以为空！");
        this.$nextTick(() => {
          if (this.$refs.queryForm) {
            this.$refs.queryForm.validateField('indicatorSystem.systemNameTab1');
          }
        });
        return;
      }

      // 2. 验证是否选择了指标
      if (this.allSelectedNodes1.size === 0) {
        this.$modal.msgError("请至少选择一个指标！");
        return;
      }

      // 3. 验证当前标签页所有叶子节点的权重
      if (!this.validateAllWeights(this.allSelectedNodes1, 'tab1')) {
        return;
      }

      this.$confirm('是否确认添加指标体系？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // --- 重组发送到后端的数据，匹配 IndicatorSystemVo 结构 ---
        const systemToSubmit = {
          // 后端 IndicatorSystemVo 中的 indicatorSystem 对象
          indicatorSystem: {
            systemName: this.indicatorSystem.systemNameTab1, // 使用 Tab1 的名称
            systemType: "0", // 设置系统类型
            // 如果后端 IndicatorSystem 实体还需要其他字段（如 description），可以在这里添加
            // description: this.form.description || '',
          },
          // 后端 IndicatorSystemVo 中的 systemType 字段 (如果后端业务逻辑依赖它，也可以加上)
          systemType: "0",
          // 后端 IndicatorSystemVo 中的 indicatorWeight 列表
          indicatorWeight: []
        };

        // 构建权重列表
        for(let i of this.allSelectedNodes1){
          const weight = this.weightMapTab1[i];
          systemToSubmit.indicatorWeight.push({
            id: i,
            subjectiveWeight: weight !== undefined ? weight : 0
          });
        }
        // --- 重组结束 ---

        addSystem(systemToSubmit).then(response => { // 发送重组后的对象
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.reset();
          this.$router.push({
            path:'/access/system/index'
          })
        }).catch(error => {
          this.$modal.msgError("添加失败：" + (error.message || "未知错误"));
        });
      })
    },

    addSystem2() {
      // 1. 验证当前标签页的体系名称 (使用 form 的验证)
      if (!this.indicatorSystem.systemNameTab2) {
        this.$modal.msgError("中国参与体系名称不可以为空！");
        this.$nextTick(() => {
          if (this.$refs.queryForm) {
            this.$refs.queryForm.validateField('indicatorSystem.systemNameTab2');
          }
        });
        return;
      }

      // 2. 验证是否选择了指标
      if (this.allSelectedNodes2.size === 0) {
        this.$modal.msgError("请至少选择一个指标！");
        return;
      }

      // 3. 验证当前标签页所有叶子节点的权重
      if (!this.validateAllWeights(this.allSelectedNodes2, 'tab2')) {
        return;
      }

      this.$confirm('是否确认添加指标体系？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // --- 重组发送到后端的数据，匹配 IndicatorSystemVo 结构 ---
        const systemToSubmit = {
          // 后端 IndicatorSystemVo 中的 indicatorSystem 对象
          indicatorSystem: {
            systemName: this.indicatorSystem.systemNameTab2, // 使用 Tab2 的名称
            systemType: "1", // 设置系统类型
            // 如果后端 IndicatorSystem 实体还需要其他字段（如 description），可以在这里添加
            // description: this.form.description || '',
          },
          // 后端 IndicatorSystemVo 中的 systemType 字段
          systemType: "1",
          // 后端 IndicatorSystemVo 中的 indicatorWeight 列表
          indicatorWeight: []
        };

        // 构建权重列表
        for(let i of this.allSelectedNodes2){
          const weight = this.weightMapTab2[i];
          systemToSubmit.indicatorWeight.push({
            id: i,
            subjectiveWeight: weight !== undefined ? weight : 0
          });
        }
        // --- 重组结束 ---

        addSystem(systemToSubmit).then(response => { // 发送重组后的对象
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.reset();
          this.$router.push({
            path:'/access/system/index'
          })
        }).catch(error => {
          this.$modal.msgError("添加失败：" + (error.message || "未知错误"));
        });
      })
    },

    filterTree(treeNodes, idsToKeep) {
      // 递归函数，用于过滤树形结构
      function traverseAndFilter(nodes) {
        let filteredNodes = [];
        for (let node of nodes) {
          if (idsToKeep.has(node.id)) {
            let newNode = {...node};
            if (newNode.children) {
              newNode.children = traverseAndFilter(newNode.children);
            }
            filteredNodes.push(newNode);
          }
        }
        console.log(filteredNodes);
        return filteredNodes;
      }
      return traverseAndFilter(treeNodes);
    },
    getSelectedNodes2() {
      // 使用 $refs 访问 el-tree 组件实例
      const checkedNodes = this.$refs.tree2.getCheckedKeys();
      const halfCheckedNodes = this.$refs.tree2.getHalfCheckedKeys();
      this.allSelectedNodes2 = new Set([...checkedNodes, ...halfCheckedNodes]);
      this.dataList3 = this.filterTree(this.dataList, this.allSelectedNodes2);
    },
    getSelectedNodes() {
      // 使用 $refs 访问 el-tree 组件实例
      const checkedNodes = this.$refs.tree.getCheckedKeys();
      const halfCheckedNodes = this.$refs.tree.getHalfCheckedKeys();
      this.allSelectedNodes1 = new Set([...checkedNodes, ...halfCheckedNodes]);
      this.dataList2 = this.filterTree(this.dataList, this.allSelectedNodes1);
    },

    // 选择图标
    selected(name) {
      this.form.icon = name;
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      getIndicatorsTree(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.dataListTab1 = [];
        this.dataListTab2 = [];
        this.dataList.forEach(item => {
          if (item.indicatorType === '0') {
            this.dataListTab1.push(item);
          } else if (item.indicatorType === '1') {
            this.dataListTab2.push(item);
          }
        });
        this.loading = false;
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      // 重置两个标签页的体系名称
      this.indicatorSystem.systemNameTab1 = '';
      this.indicatorSystem.systemNameTab2 = '';
      // 重置权重列表
      this.indicatorSystem.indicatorWeight = [];
      // 清空两个标签页的权重映射
      this.weightMapTab1 = {};
      this.weightMapTab2 = {};
      // 重置选中节点集合
      this.allSelectedNodes1 = new Set();
      this.allSelectedNodes2 = new Set();
      // 清空表格数据
      this.dataList2 = [];
      this.dataList3 = [];
      // 清除树的选中状态
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedKeys([]);
      }
      if (this.$refs.tree2) {
        this.$refs.tree2.setCheckedKeys([]);
      }
      // 重新获取数据
      this.getList();
      // 清除表单验证错误提示
      if (this.$refs.queryForm) {
        this.$refs.queryForm.clearValidate();
      }
    },
    handleSelect() {
      this.getSelectedNodes();
    },
    handleSelect2() {
      this.getSelectedNodes2();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      getMenu(row.menuId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改菜单";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.menuId != undefined) {
            updateMenu(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.menuName + '"的数据项？').then(function () {
        return delMenu(row.menuId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    }
  }
};
</script>

<style scoped>
.center {
  text-align: center;
}

.downbutton {
  text-align: center;
  margin-top: 20px;
}

/* 权重输入框样式 */
::v-deep .el-input-number .el-input__inner {
  text-align: left;
  padding-left: 10px;
}

/* 必填提示样式 */
.required-tip {
  color: #f56c6c;
  font-size: 12px;
  font-weight: bold;
  animation: blink 1.5s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

/* 树形控件样式优化 */
::v-deep .el-tree {
  margin-top: 10px;
}

::v-deep .el-tree-node__content {
  height: 35px;
  line-height: 35px;
}

/* 表格样式优化 */
::v-deep .el-table {
  margin-top: 10px;
}

/* 添加样式以确保表单验证错误时输入框变红 */
::v-deep .el-form-item.is-error .el-input__inner {
  border-color: #f56c6c;
}

</style>
